import React from 'react';
import {Input, Button, Form, Row, Col, Select, DatePicker, Icon, Popconfirm} from 'antd';
import moment from 'moment';
import Tools from '@untils/tools.jsx';
import RCModal from '@components/modal/index.jsx';
import {sex, polityState, voluntaryActivityType, REG} from '@assets/config/global.js';

import './scss/vol_msg_modal.scss';

const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
const columns = [{
    title: '活动名称',
    key: 'name',
    span: 3,
}, {
    title: '活动组织',
    key: 'orgName',
    span: 4,
}, {
    title: '活动类型',
    key: 'voluntaryActivityType',
    span: 4,
}, {
    title: '活动时间',
    key: 'gmtStart,gmtEnd',
    span: 9,
}, {
    title: '活动时长',
    key: 'duration',
    span: 2,
}, {
    title: '操作',
    key: '',
    span: 2,
}];

class VolMsgModal extends React.Component {

    constructor(props) {
        super(props);
        this.state = {

            list: [],
            rowData: {},
        };
        this.setCallback = Tools.setCallback.bind(this);
        this.originalList = [];
    }

    componentDidMount() {
        this.props.form.validateFields();
        this.dealPropsData();
    }

    // 处理porps数据
    dealPropsData() {
        let rowData = Tools.objectAssign(this.props.data || {}, {});
        this.originalList = [...rowData.voluntaryActivities || [], ...[]];
        //objectAssign
        let list = this.originalList.map(item => {
            let obj = {
                disabled: true,
                hasError: false
            };

            Object.keys(item).map(key => obj[key] = item[key]);
            return obj;
        });
        this.setCallback({rowData, list});
    }

    // 判断是否可以提交
    hasErrors(fieldsError) {
        let disabled = Object.keys(fieldsError).some(field => fieldsError[field]);
        return disabled;
    }

    // 点击提交
    submitForm() {
        let formInfo = this.props.form.getFieldsValue();
        let {list: voluntaryActivities} = this.state;
        let obj = {...formInfo, voluntaryActivities};
        this.props.submitForm(obj);
        this.props.form.resetFields();
    }

    // 取消关闭按钮
    onCancel() {
        this.props.form.resetFields();
        this.originalList = [];
        this.setCallback({list: [], rowData: {}}, this.props.cancelForm);
    }

    // 点击编辑
    handleEdit(rIndex) {
        let {list} = this.state;
        list[rIndex].disabled = false;
        this.setCallback({list});
    }

    // 点击取消
    handleCancal(Rindex) {
        let {list, currentData = {disabled: true, hasError: false}} = this.state;

        // 添加后没有保存的取消 直接删除此列
        if (list[Rindex].hasOwnProperty('newAdd')) {
            list.splice(Rindex, 1);
        } else {
            Object.keys(this.originalList[Rindex]).map(item => {
                currentData[item] = this.originalList[Rindex][item];
                return null;
            });
            list[Rindex] = currentData;
        }

        this.setCallback({list});
    }

    // 保存操作
    handleSave(Rindex) {
        let {list} = this.state;
        let obj = {};
        list[Rindex].disabled = true;
        delete list[Rindex].newAdd;

        Object.keys(list[Rindex]).map(item => {
            void(item === 'newAdd' ? 0 : obj[item] = list[Rindex][item]);
            return null;
        });

        this.originalList[Rindex] = obj;
        this.setCallback({list});
    }

    del(e, id) {

    }

    volMsgChange(val, Rindex, key, node) {
        let {list} = this.state;
        let currentData = list[Rindex];

        // 时间范围
        if (key === 'gmtStart,gmtEnd') {
            currentData['gmtStart'] = val[0];
            currentData['gmtEnd'] = val[1];
        } else {
            currentData[key] = val;
        }

        // 验证
        if (key === 'name') {
            void(val.trim() === '' ? node.className = 'item-ipt-parent error' : node.className = 'item-ipt-parent');
        } else if (key === 'voluntaryActivityType') {
            void(isNaN(val - 0) ? node.className = 'item-ipt-parent error' : node.className = 'item-ipt-parent');
        } else if (key === 'duration') {
            void(!(REG.num).test(currentData.duration) ? node.className = 'item-ipt-parent error' : node.className = 'item-ipt-parent');
        } else {

        }
        let hasError = !(currentData.name.trim() && (REG.num).test(currentData.voluntaryActivityType) && (REG.num).test(currentData.duration));
        currentData.hasError = hasError;
        list[Rindex] = currentData;
        this.setCallback({list});
    }

    // 添加
    handleAdd = () => {
        const {list} = this.state;
        const newData = {
            disabled: false,
            hasError: true,
            newAdd: true,
            name: '',
            orgName: ``,
            voluntaryActivityType: '',
            gmtStart: '',
            gmtEnd: '',
            duration: ''
        };
        this.setCallback({list: [...list, newData]});
    }

    // 气泡删除
    handlePop(Rindex) {
        let {list} = this.state;
        list.splice(Rindex, 1);
        this.originalList.splice(Rindex, 1);
        this.setCallback({list});
    }

    render() {
        let {modalVisible = false, showFooter = false, data = {}} = this.props;
        let {list = []} = this.state;

        const formItemLayout = {
            colon: false,
            labelCol: {
                span: 8
            },
            wrapperCol: {
                span: 16
            }
        };
        const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;

        const rules = [{required: true, message: '必填项！'}];
        const nameError = isFieldTouched('name') && getFieldError('name');// 户主姓名不能为空
        const sexError = isFieldTouched('sex') && getFieldError('sex');// 性别不能为空
        const idCardError = isFieldTouched('idCard') && getFieldError('idCard');//身份证号不能为空
        const phoneError = isFieldTouched('phone') && getFieldError('phone');// 联系电话不能为空
        const durationError = isFieldTouched('duration') && getFieldError('duration');// 时长不能为空

        const canAppend = list.some(item => !!item.newAdd);
        // 验证数据有错误 或 保存的没有保存
        const dataError = list.some(item => item.hasError === true || item.disabled === false);

        return (
            <RCModal
                width={1000}
                visible={modalVisible}
                showFooter={showFooter}
                title='志愿者信息'
                footerText={{okText: '提交'}}
                disabled={this.hasErrors(getFieldsError()) || dataError}
                onOk={this.submitForm.bind(this)}
                onCancel={this.onCancel.bind(this)}
            >
                <div className="vol-msg-modal">
                    <Form layout='horizontal'>
                        <div className="modal-content">
                            <Row>
                                <Col span={8}>
                                    <FormItem
                                        label='姓名'
                                        {...formItemLayout}
                                        validateStatus={nameError ? 'error' : ''}
                                        help={nameError || ''}
                                    >
                                        {
                                            getFieldDecorator('name', {initialValue: data.name || '', rules})(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem label='性别' {...formItemLayout}
                                              validateStatus={sexError ? 'error' : ''}
                                              help={sexError || ''}
                                    >
                                        {
                                            getFieldDecorator('sex', sex[data.sex] ? {
                                                initialValue: data.sex || 0,
                                                rules
                                            } : {rules})(
                                                <Select style={{width: '100%'}} placeholder='请选择'>
                                                    {
                                                        Object.keys(sex).map((item, index) => {
                                                            return (
                                                                <Option value={sex[item].id}
                                                                        key={index}>{sex[item].name}</Option>
                                                            )
                                                        })
                                                    }
                                                </Select>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        label='服务时长'
                                        {...formItemLayout}
                                        validateStatus={durationError ? 'error' : ''}
                                        help={durationError || ''}
                                    >
                                        {
                                            getFieldDecorator('duration', {
                                                initialValue: data.duration || '',
                                                rules: [...rules, {pattern: RegExp(REG.num, 'g'), message: '服务时长输入有误！'}]
                                            })(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem
                                        label='身份证号'
                                        {...formItemLayout}
                                        validateStatus={idCardError ? 'error' : ''}
                                        help={idCardError || ''}
                                    >
                                        {
                                            getFieldDecorator('idCard',
                                                {
                                                    initialValue: data.idCard || '',
                                                    rules: [...rules, {
                                                        pattern: RegExp(REG.idCard, 'g'),
                                                        message: '身份证号码输入有误！'
                                                    }]
                                                })(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        label='手机号码'
                                        {...formItemLayout}
                                        validateStatus={phoneError ? 'error' : ''}
                                        help={phoneError || ''}
                                    >
                                        {
                                            getFieldDecorator('phone', {
                                                initialValue: data.phone || '',
                                                rules: [...rules, {
                                                    pattern: RegExp(REG.phone, 'g'),
                                                    message: '手机号码输入有误！'
                                                }]
                                            })(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        label='年龄'
                                        {...formItemLayout}>
                                        {
                                            getFieldDecorator('age', {initialValue: data.age || ''})(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem
                                        label='家庭住址'
                                        {...formItemLayout}
                                    >
                                        {
                                            getFieldDecorator('address', {initialValue: data.address || ''})(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        label='籍贯'
                                        {...formItemLayout}
                                    >
                                        {
                                            getFieldDecorator('nativePlace', {initialValue: data.nativePlace || ''})(
                                                <Input placeholder='请输入'/>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem
                                        label='政治面貌'
                                        {...formItemLayout}
                                    >
                                        {
                                            getFieldDecorator('polityState', polityState[data.polityState]
                                                ? {initialValue: data.polityState || 1}
                                                : {})(
                                                <Select style={{width: '100%'}} placeholder='请选择'>
                                                    {

                                                        Object.keys(polityState).map((item, index) => {
                                                            return (
                                                                <Option value={polityState[item].id}
                                                                        key={index}>{polityState[item].name}</Option>
                                                            )
                                                        })
                                                    }
                                                </Select>
                                            )
                                        }
                                    </FormItem>
                                </Col>
                            </Row>
                        </div>
                    </Form>

                    <p className='list-title'>组织活动</p>
                    <div className="vol-active-list">
                        <div className="table-header">
                            <Row>
                                {
                                    columns.map((item, index) => {
                                        return (
                                            <Col key={index} span={item.span}>
                                                <div className="list-header-item">{item.title}</div>
                                            </Col>
                                        );
                                    })
                                }
                            </Row>
                        </div>
                        <ul className="active-list">
                            {
                                list.map((data, Rindex) => {
                                    let liDom = (
                                        <li className="list-item" key={Rindex}>
                                            {
                                                columns.map((column, Cindex) => {
                                                    let keys = column.key ? column.key.split(',') : [];
                                                    let val = '';
                                                    for (let k = 0; k < keys.length; k++) {
                                                        val === '' ? val += data[keys[k]] : val += ('_' + data[keys[k]]);
                                                    }
                                                    let CDOM = null;
                                                    // 操作项
                                                    if (column.key === '') {
                                                        CDOM = showFooter
                                                            ? (
                                                                <Col span={column.span} key={Cindex}>
                                                                    <div className="item-ipt-parent">
                                                                        <Button type='default'
                                                                                className={`${data.disabled ? 'active' : ''}`}
                                                                                onClick={() => this.handleEdit(Rindex)}
                                                                        >编辑</Button>
                                                                        <Popconfirm
                                                                            placement="top"
                                                                            title='是否确认删除信息？'
                                                                            onConfirm={() => this.handlePop(Rindex)}
                                                                            okText="确定"
                                                                            cancelText="取消"
                                                                        >
                                                                            <Button
                                                                                className={`${data.disabled ? 'active' : ''}`}>删除</Button>
                                                                        </Popconfirm>

                                                                        <Button
                                                                            disabled={data.hasError}
                                                                            className={`${!data.disabled ? 'active' : ''}`}
                                                                            onClick={() => this.handleSave(Rindex)}
                                                                        >保存</Button>
                                                                        <Button
                                                                            className={`${!data.disabled ? 'active' : ''}`}
                                                                            onClick={() => this.handleCancal(Rindex)}
                                                                        >取消</Button>
                                                                    </div>
                                                                </Col>
                                                            )
                                                            : (
                                                                <Col span={column.span} key={Cindex}>
                                                                    <div className="item-ipt-parent">---</div>
                                                                </Col>
                                                            )
                                                        //  活动类型
                                                    } else if (column.key === 'voluntaryActivityType') {
                                                        CDOM = (
                                                            <Col span={column.span} key={Cindex}>
                                                                <div className="item-ipt-parent"
                                                                     ref={node => this[`_${Rindex}${Cindex}`] = node}>
                                                                    <Select style={{width: '100%'}} placeholder='请选择'
                                                                            value={voluntaryActivityType[val] ? voluntaryActivityType[val].id : []}
                                                                            disabled={data.disabled}
                                                                            onChange={(val) => {
                                                                                this.volMsgChange(val, Rindex, column.key, this[`_${Rindex}${Cindex}`])
                                                                            }}
                                                                    >
                                                                        {

                                                                            Object.keys(voluntaryActivityType).map((item, index) => {
                                                                                return (
                                                                                    <Option
                                                                                        value={voluntaryActivityType[item].id}
                                                                                        key={index}>{voluntaryActivityType[item].name}</Option>
                                                                                )
                                                                            })
                                                                        }
                                                                    </Select>
                                                                </div>
                                                            </Col>
                                                        )
                                                        // 时间选择
                                                    } else if (column.key === 'gmtStart,gmtEnd') {
                                                        // val= '_';
                                                        let dateFormat = 'YYYY-MM-DD HH:mm:ss';
                                                        // moment(null).format(dateFormat)
                                                        let gmtStart = val.split('_')[0] ? moment(val.split('_')[0], dateFormat) : null;
                                                        let gmtEnd = val.split('_')[1] ? moment(val.split('_')[1], dateFormat) : null;
                                                        CDOM = (
                                                            <Col span={column.span} key={Cindex}>
                                                                <div className="item-ipt-parent"
                                                                     ref={node => this[`_${Rindex}${Cindex}`] = node}>
                                                                    <RangePicker
                                                                        style={{width: '100%'}}
                                                                        showTime={true}
                                                                        disabled={data.disabled}
                                                                        format={dateFormat}
                                                                        value={[gmtStart, gmtEnd]}
                                                                        onChange={(data, dataString) => {
                                                                            this.volMsgChange(dataString, Rindex, column.key, this[`_${Rindex}${Cindex}`])
                                                                        }}
                                                                    />
                                                                </div>
                                                            </Col>
                                                        )
                                                    } else {
                                                        CDOM = (
                                                            <Col span={column.span} key={Cindex}>
                                                                <div className="item-ipt-parent"
                                                                     ref={node => this[`_${Rindex}${Cindex}`] = node}>
                                                                    <Input
                                                                        value={val}
                                                                        disabled={data.disabled}
                                                                        onChange={(e) => {
                                                                            let val = e.target.value;
                                                                            // Rindex 哪条数据  column.key 哪条数据
                                                                            this.volMsgChange(val, Rindex, column.key, this[`_${Rindex}${Cindex}`])
                                                                        }}
                                                                    />
                                                                </div>
                                                            </Col>
                                                        )
                                                    }

                                                    return CDOM;
                                                })
                                            }
                                        </li>
                                    );
                                    return liDom;
                                })
                            }
                        </ul>
                        {
                            !showFooter
                                ? null
                                : <div className="append-vol-msg">
                                    <Button
                                        className="add-btn"
                                        type='primary'
                                        disabled={canAppend}
                                        onClick={() => this.handleAdd()}
                                    >
                                        <Icon type='plus'></Icon>
                                        <span className="txt">新增</span>
                                    </Button>
                                </div>
                        }
                    </div>
                </div>

            </RCModal>
        )
    }
}

VolMsgModal = Form.create({})(VolMsgModal);
export default VolMsgModal;